package org.example.sb_api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.example.sb_api.common.Result;
import org.example.sb_api.entity.Vehicle;
import org.example.sb_api.mapper.VehicleMapper;
import org.example.sb_api.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VehicleServiceImpl implements VehicleService {

    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public Result getVehicleList(Long userId) {
        List<Vehicle> vehicles = vehicleMapper.selectList(
            new QueryWrapper<Vehicle>().eq("user_id", userId)
        );
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", vehicles.size());
        result.put("rows", vehicles);
        result.put("code", 200);
        
        return Result.success(result);
    }

    @Override
    public Result getVehicleDetail(Long id) {
        Vehicle vehicle = vehicleMapper.selectById(id);
        if (vehicle == null) {
            return Result.error("车辆不存在");
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("data", vehicle);
        result.put("code", 200);
        
        return Result.success(result);
    }

    @Override
    public Result setDefaultVehicle(Long id) {
        Vehicle vehicle = vehicleMapper.selectById(id);
        if (vehicle == null) {
            return Result.error("车辆不存在");
        }
        
        // 先将该用户的所有车辆设置为非默认
        vehicleMapper.update(null,
            new UpdateWrapper<Vehicle>()
                .eq("user_id", vehicle.getUserId())
                .set("selected_state", 0)
        );
        
        // 设置指定车辆为默认
        vehicle.setSelectedState(1);
        vehicleMapper.updateById(vehicle);
        
        return Result.success(null);
    }
} 